package com.mengwen.backstage.service.impl;

import com.google.gson.Gson;
import com.mengwen.backstage.config.QiniuConfig;
import com.mengwen.backstage.service.FileService;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;

/**
 * @author LiangYonghui
 * @date 2020/4/19 13:32
 * @description 文件上传服务类接口实现类
 */
@Service
@Slf4j
public class FileServiceImpl implements FileService {

    @Autowired
    QiniuConfig qiniuConfig;


    @Override
    public String uploadImageWithPath(String path) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region0());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        String accessKey = qiniuConfig.getQiniuAccessKey();
        String secretKey = qiniuConfig.getQiniuSecretKey();
        String bucket = qiniuConfig.getBuckName();
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = null;
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        String result = null;
        try {
            Response response = uploadManager.put(path, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            result = putRet.hash;
            log.info("putRet.key:" + putRet.key);
            log.info("putRet.hash:" + putRet.hash);

        } catch (QiniuException ex) {
            Response r = ex.response;
            log.info(r.toString());

            try {
                log.info(r.bodyString());

            } catch (QiniuException ex2) {
                //ignore
            }
        }
        return qiniuConfig.getWebDomain()+'/' + result;
    }

    @Override
    public boolean deleteImageWithFileName(String fileName) {
        boolean result = false;
        File file = new File(qiniuConfig.getLocalImgPath() + "/" + fileName);
        if (file.exists()) {
            file.delete();
            result = true;
            log.info("图片：" + fileName + ",删除成功");
        }
        return result;

    }
}
